from flask import render_template,jsonify,session,request,g
from flask import current_app
import logging
from . import index_bp
from info.models import User,News,Category
from info.utitls.response_code import RET
from info import redis_store,constants
from info.utitls.common import user_login_data

# 使用蓝图
@index_bp.route("/")
@user_login_data
def index():

    # user_id = session.get("user_id")
    #
    # user = None
    #
    # if user_id:
    #
    #     try:
    #
    #         user = User.query.get(user_id)
    #
    #     except Exception as e:
    #
    #         current_app.logger.error(e)
    #
    #         return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")

    user = g.user

    # if user:
    #
    #     user_dict = user.to_dict()

    # 新闻点击排行榜数据
    try:
        news_rank_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)

    except Exception as e:

        current_app.logger.error(e)

        return jsonify(errno=RET.DBERR, errmsg="查询新闻数据异常")

    news_dict_list = []

    for new_obj in news_rank_list if news_rank_list else []:

        news_dict = new_obj.to_dict()

        news_dict_list.append(news_dict)

    # 查询分类数据
    try:

        categaries = Category.query.all()

    except Exception as e:

        current_app.logger.error(e)

        return jsonify(errno=RET.DBERR, errmsg="查询分类数据异常")

    categaries_dict_list = []

    for categary in categaries if categaries else []:

        categary_dict = categary.to_dict()

        categaries_dict_list.append(categary_dict)

    data = {
        "user_info": user.to_dict() if user else None,
        "news_rank_list": news_dict_list,
        "categaries": categaries_dict_list
    }

    return render_template("news/index.html", data=data)


@index_bp.route("/favicon.ico")
def get_favicon():

    """内部发送静态文件到浏览器的方法"""

    return current_app.send_static_file("news/favicon.ico")


@index_bp.route('/news_list')
def news_list():
    """获取新闻列表数据后端接口"""
    """
    +    1.获取参数
    +        1.1 cid:分类id（表明要获取那个分类对应的新闻数据）
    +            page:当前页码（默认值：1）， 
    +            per_page:每一页多少条新闻（默认值：10）
    +    2.参数校验
    +        2.1 cid是否为空
    +        2.2 数据格式校验是否能转换成int类型
    +    3.逻辑处理
    +        3.1 调用分页方法paginate查询新闻列表数据
    +        3.2 将新闻对象列表转换成新闻字典列表 
    +    4.返回值
   """
    param_dict = request.args

    cid = param_dict.get("cid")

    page = param_dict.get("page", 1)

    per_page = param_dict.get("per_page", 10)

    if not cid:

        current_app.logger.error("参数不足")

        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    try:

        cid = int(cid)

        page = int(page)

        per_page = int(per_page)

    except Exception as e:

        current_app.logger.error(e)

        return jsonify(errno=RET.PARAMERR, errmsg="参数格式错误")

    filter_list = []

    if cid != 1:

        filter_list.append(News.category_id == cid)

    try:

        paginate = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(page,per_page, False)

        news_list = paginate.items

        current_page = paginate.page

        total_page = paginate.pages

    except Exception as e:

        current_app.logger.error(e)

        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象列表异常")

    news_dict_list = []

    for news in news_list if news_list else []:

        news_dict_list.append(news.to_dict())

    data = {
        "newsList": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return jsonify(errno=RET.OK, errmsg="新闻列表数据查询成功", data=data)